#encoding=utf8
'''
Created on Sep 6, 2015

@author: jingyang <jingyang@smalltreemedia.com>
'''
from celery.task import task
import datetime
from utils import this_week
import settings
from core.admin_site import get_context
from app_info.models import AppVersion
from django.template.loader import get_template
from notification.models import ReportReceiver
from django.template.context import Context
from django.core.mail.message import EmailMessage


@task()
def weekly_report():
    today = datetime.date.today()
#    if not today.isocalendar()[2] == 1:
#        print 'not today...'
#        return
    print 'Generate report email...'
    date = today - datetime.timedelta(days=7)
    monday, sunday = this_week(date)
    if settings.DEBUG:
        domain = 'localhost:8000'
    else:
        if settings.STAGING:
            domain = 'pts.stm.com'
        else:
            domain = 'pts.mokitech.com'
    ctx = {'monday': monday, 'sunday': sunday, 'domain': domain}
    ctx.update(get_context())

    metrics = []

    for n, label in enumerate(['Apps Released In Last Week',
        'Apps Submitted In Last Week', 'Apps In Review']):
        if n == 0:
            data = AppVersion.objects.filter(status='L', date_released__range=(monday, sunday))
        elif n == 1:
            data = AppVersion.objects.filter(status__in=['S', 'L'], date_submitted__range=(monday, sunday))
        else:
            data = AppVersion.objects.filter(status='S')
        metrics.append({'label': label, 'count': data.count(), 'data': data})

    ctx.update({'data_group': metrics})

    t = get_template('base/weekly_email.html')
    for r in ReportReceiver.objects.filter(is_active=True):
        ctx.update({'r': r})
        html = t.render(Context(ctx))
        msg = EmailMessage('Chengdu Production Weekly Report (%s)' % today, html, settings.EMAIL_HOST_USER, [r.email])
        msg.content_subtype = 'html'
        msg.send()
    print 'Weekly Report Sent'
